import Vue from 'vue'
import axios from 'axios'
import { getCache } from "@/utils/cache";
import {
	Message
} from 'element-ui';

// axios.defaults.baseURL = '/api';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
// export const baseURL = process.env.NODE_ENV === 'development' ? '/api' : '/api';
axios.defaults.baseURL = process.env.NODE_ENV === 'production' ? '/api/fanligo' : '/api';


const http = axios.create({
	// baseURL: baseURL,
	timeout: 10000,
	headers: {
		// 'Content-Type': 'application/x-www-form-urlencoded'
	}
})

//在实例创建后改变默认值
// http.defaults.headers.common ['Authorization'] = AUTH_TOKEN;
// http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

var CancelToken = axios.CancelToken;
var source = CancelToken.source();

//添加请求拦截器
http.interceptors.request.use(
	function(config) {
		//在发送请求之前做某事
		console.log('http config:', config);
		const method = config.method;
		console.log('http method:', method);
		const accessToken = getCache('access_token');
		if (accessToken != null) {
		    config.headers['access_token'] = accessToken;
		}
		
		// else {
		// 	window.location.href = "http://127.0.0.1:8081/#/login";
		// }
		return config;
	},
	function(error) {
		//请求错误时做些事
		Message.error(error.response.data);
		return Promise.reject(error);
	});

//添加响应拦截器
http.interceptors.response.use(
	function(response) {
		//对响应数据做些事
		const httpRespStatus = response.status;
		console.log('http response.status:', httpRespStatus);
		console.log('http response:', response);
		const code = response.status;
		if (200 == code) {
			if (null == response.data) {
				Message({
					message: response.data.message,
					type: 'success'
				});
			}
		} else if (1 != code) {
			Message({
				message: response.data.message,
				type: 'warning'
			});
			switch (code) {
				case 4011:
					auth.logout();
					break;
				case 4031:
					auth.login();
					http.defaults.headers.common['accessToken'] = auth.getToken();
					break;
				default:
					break;
			}
		}
		return response.data;
	},
	function(error) {
		console.log('http response error:', error);
		//请求错误时做些事
		Message.error(response.data.message);
		return Promise.reject(error);
	});


Vue.prototype.$http = http; //使用axios实例发http请求

export default http;
